const bcrypt = require("bcryptjs");
const { query, db } = require("../../db/db");
const {
  createToken,
  createToken_refresh,
} = require("../../jsonwebtoken/index");
const salt = bcrypt.genSaltSync(10);

async function RegisterOrLogin(req, res) {
  const PhoneNumber = req.body.PhoneNumber;
  const PassWord = req.body.PassWord;

  //查询手机号是否已经注册
  const select_phone_register = "Select *  From User Where PhoneNumber=?";

  const select_phone_register_res = await query(select_phone_register, [
    PhoneNumber,
  ]);
  if (select_phone_register_res.length > 0) {
    //验证密码，执行登录
    const compareResult = bcrypt.compareSync(
      PassWord,
      select_phone_register_res[0].PassWord
    );
    console.log("333", compareResult);

    if (compareResult) {
      res.send({
        status: 0,
        accessToken: createToken({
          PhoneNumber: PhoneNumber,
        }),
        refreshToken: createToken_refresh({
          PhoneNumber: PhoneNumber,
        }),
        username: select_phone_register_res[0].UserName,
        HeaderImg: select_phone_register_res[0].HeaderImg,
        UserId: select_phone_register_res[0].UserId,
      });
    } else {
      res.send({
        status: 1,
        Message: "密码错误",
      });
    }
  } else {
    //执行注册
    const PassWordHash = bcrypt.hashSync(PassWord, salt);
    const insert_user_info =
      "Insert Into User (PhoneNumber,PassWord) Values(?,?)";

    await query(insert_user_info, [PhoneNumber, PassWordHash]);

    res.send({
      status: 0,
      Message: "注册成功!",
    });
  }
}

module.exports = { RegisterOrLogin };
